import { getPool } from '../config/database';

interface Profile {
  id?: number;
  userId: number;
  address?: string;
  photo?: string;
  gender?: number;
}

export class ProfileModel {
  /**
   * 通过用户ID获取资料
   */
  static async findByUserId(userId: number): Promise<Profile | null> {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM profile WHERE userId = ?', [userId]);
    const profiles = rows as Profile[];
    return profiles.length ? profiles[0] : null;
  }

  /**
   * 更新用户资料
   */
  // Partial<Profile> 类型表示 profile 对象的部分属性可以为 undefined
  static async update(userId: number, profile: Partial<Profile>): Promise<boolean> {
    const pool = getPool();
    
    // 检查资料是否存在
    const existing = await this.findByUserId(userId);
    
    if (existing) {
      // 更新现有资料
      const [result] = await pool.query(
        'UPDATE profile SET gender = ?, address = ?, photo = ? WHERE userId = ?',
        [profile.gender, profile.address, profile.photo, userId]
      );
      return (result as any).affectedRows > 0;
    } else {
      // 创建新资料
      const [result] = await pool.query(
        'INSERT INTO profile (userId, gender, address, photo) VALUES (?, ?, ?, ?)',
        [userId, profile.gender||2, profile.address||'', profile.photo||'']
      );
      return (result as any).affectedRows > 0;
    }
  }
}
